import 'dart:math';

import '../../public.dart';

class WalletBankCardsWidget extends StatefulWidget {
  final UserModel model;

  const WalletBankCardsWidget({super.key, required this.model});

  @override
  State<WalletBankCardsWidget> createState() => _WalletBankCardsWidgetState();
}

class _WalletBankCardsWidgetState extends State<WalletBankCardsWidget> {
  @override
  Widget build(BuildContext context) {
    if (widget.model.bankCardList.isEmpty) {
      // 空状态占位视图：提示用户添加银行卡
      return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Container(
          width: double.infinity,
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.grey[50],
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: Colors.grey.shade200),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const Icon(
                Icons.account_balance_wallet_outlined,
                size: 48,
                color: Colors.blue,
              ),
              const SizedBox(height: 12),
              const Text(
                'No bank cards yet',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
              ),
              const SizedBox(height: 8),
              Text(
                'Add a bank card to withdraw funds quickly and securely',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 13, color: Colors.grey[600]),
              ),
              const SizedBox(height: 14),
              ElevatedButton(
                onPressed: () async {
                  final added = await RouterHelper.navigator.pushNamed(
                    Routers.addBankCard,
                  );
                  if (added != null && (added as bool)) {
                    await widget.model.getBankCardList();
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 20,
                    vertical: 10,
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: const Text('Add Bank Card'),
              ),
            ],
          ),
        ),
      );
    }

    // 使用层叠卡片样式展示，多张卡片重叠，超出显示 +N
    final cards = widget.model.bankCardList;
    final total = cards.length;
    final displayCount = min(total, 3);
    final cardHeight = 140.0;
    final overlapX = 18.0; // 每张卡水平偏移
    final overlapY = 8.0; // 每张卡垂直偏移

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: SizedBox(
        height: cardHeight + overlapY * (displayCount - 1),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            for (int i = 0; i < displayCount; i++)
              Positioned(
                left: i * overlapX,
                top: i * overlapY,
                child: _buildStackCard(cards[i], i, total),
              ),

            if (total > displayCount)
              Positioned(
                left: displayCount * overlapX,
                top: displayCount * overlapY + cardHeight / 2 - 16,
                child: Container(
                  width: 48,
                  height: 48,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(24),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: 8,
                        offset: const Offset(0, 4),
                      ),
                    ],
                  ),
                  alignment: Alignment.center,
                  child: Text(
                    '+${total - displayCount}',
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  // 构建单张层叠风格的银行卡卡片
  Widget _buildStackCard(
    WithdrawBankCardComboxDto bankCard,
    int index,
    int total,
  ) {
    final icon = CryptoUtil.decryptData(bankCard.iconUrl);
    final width = ScreenUtil.width - 32 - index * 18.0;
    final gradientColors = [
      const Color(0xFF5563FF).withOpacity(1.0 - index * 0.08),
      const Color(0xFF4F46E5).withOpacity(1.0 - index * 0.06),
    ];

    return GestureDetector(
      onTap: () {
        // 点击卡片可进入管理或选择（当前保持打开移除确认）
      },
      child: Container(
        width: width,
        height: 140,
        margin: const EdgeInsets.only(right: 8),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: gradientColors,
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(14),
          boxShadow: [
            BoxShadow(
              color: Colors.black12,
              blurRadius: 12,
              offset: const Offset(0, 6),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 银行图标
                Container(
                  width: 36,
                  height: 36,
                  decoration: BoxDecoration(
                    color: Colors.white24,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: icon != null
                      ? Image.network(
                          icon,
                          width: 24,
                          height: 24,
                          fit: BoxFit.contain,
                        )
                      : const Icon(
                          Icons.account_balance,
                          color: Colors.white,
                          size: 20,
                        ),
                ),
                const Spacer(),
                // 移除按钮（小）
                GestureDetector(
                  onTap: () => _showRemoveBankCardDialog(
                    bankCard,
                    widget.model,
                    context,
                  ),
                  child: Container(
                    width: 34,
                    height: 34,
                    decoration: BoxDecoration(
                      color: Colors.white24,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Icon(
                      Icons.close,
                      color: Colors.white,
                      size: 16,
                    ),
                  ),
                ),
              ],
            ),
            const Spacer(),
            // 卡号和 chip 风格
            Row(
              children: [
                Container(
                  width: 40,
                  height: 28,
                  decoration: BoxDecoration(
                    color: Colors.white24,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: const Icon(
                    Icons.credit_card,
                    color: Colors.white,
                    size: 18,
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    _formatCardNumber(bankCard.bankCard ?? ''),
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                      letterSpacing: 1.8,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              bankCard.accountName ?? 'Account Name',
              style: TextStyle(
                color: Colors.white.withOpacity(0.9),
                fontSize: 13,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 格式化银行卡号显示
  String _formatCardNumber(String cardNumber) {
    if (cardNumber.isEmpty) return '';
    String? cardNo = CryptoUtil.decryptData(cardNumber);
    return cardNo ?? '';
  }

  // 显示移除银行卡确认对话框
  void _showRemoveBankCardDialog(
    WithdrawBankCardComboxDto bankCard,
    UserModel model,
    BuildContext context,
  ) {
    final icon = CryptoUtil.decryptData(bankCard.iconUrl);
    BrnDialogManager.showConfirmDialog(
      context,
      title: 'Remove Bank Card',
      messageWidget: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Are you sure you want to remove this bank card?',
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  icon != null
                      ? Image.network(
                          icon,
                          width: 24,
                          height: 24,
                          errorBuilder: (context, error, stackTrace) => Icon(
                            Icons.account_balance,
                            color: Colors.white,
                            size: 20,
                          ),
                        )
                      : Icon(
                          Icons.account_balance,
                          color: Colors.white,
                          size: 20,
                        ),
                  const SizedBox(width: 12),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        bankCard.bankCardType ?? 'Bank Card',
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: Colors.black87,
                        ),
                      ),
                      Text(
                        _formatCardNumber(bankCard.bankCard ?? ''),
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                          letterSpacing: 1,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      confirm: 'Remove',
      cancel: 'Cancel',
      onCancel: () {
        Navigator.of(context).pop();
      },
      onConfirm: () async {
        Navigator.of(context).pop();
        await _removeBankCard(bankCard, model, context);
      },
    );
  }

  // 执行移除银行卡操作
  Future<void> _removeBankCard(
    WithdrawBankCardComboxDto bankCard,
    UserModel model,
    BuildContext context,
  ) async {
    try {
      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext dialogContext) {
          return const Center(child: CircularProgressIndicator());
        },
      );

      // 调用解绑银行卡API
      await BankCardApi.unbindingByUser(bankCard.bankCardId!);

      // 关闭加载提示
      if (mounted) {
        Navigator.of(context).pop();
      }

      await model.getBankCardList();
      if (mounted) {
        // 显示成功提示
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Bank card removed successfully'),
            backgroundColor: Colors.green,
            duration: Duration(seconds: 2),
          ),
        );
      }
    } catch (e) {
      // 关闭加载提示
      if (mounted) {
        Navigator.of(context).pop();
      }
      // 显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: ${e.toString()}'),
            backgroundColor: Colors.red,
            duration: Duration(seconds: 3),
          ),
        );
      }
    }
  }
}
